package com.mornd.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mornd.gulimall.product.entity.AttrGroup;
import com.mornd.gulimall.product.entity.Category;
import com.mornd.gulimall.product.mapper.AttrGroupMapper;
import com.mornd.gulimall.product.service.IAttrGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mornd.gulimall.product.service.ICategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * <p>
 * 属性分组 服务实现类
 * </p>
 *
 * @author mornd
 * @since 2023-07-23
 */
@Service
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupMapper, AttrGroup> implements IAttrGroupService {
    @Resource
    private ICategoryService categoryService;

    @Override
    public IPage<AttrGroup> list(AttrGroup attrGroup) {
        // 分页信息
        IPage<AttrGroup> page = new Page<>(attrGroup.validPageNum(), attrGroup.validPageSize());
        // 查询条件
        LambdaQueryWrapper<AttrGroup> qw = Wrappers.<AttrGroup>lambdaQuery().orderByAsc(AttrGroup::getSort);
        qw.eq(attrGroup.getCatelogId() != null, AttrGroup::getCatelogId, attrGroup.getCatelogId());
        qw.and(StringUtils.hasText(attrGroup.getKey()), (wrapper) -> {
            wrapper.like(AttrGroup::getAttrGroupName, attrGroup.getKey())
                    .or().like(AttrGroup::getDescript, attrGroup.getKey());
        });

        super.page(page, qw);

        for (AttrGroup record : page.getRecords()) {
            Optional<Category> category = categoryService.getCacheById(record.getCatelogId());
            category.ifPresent(cat -> record.setCatelogName(cat.getName()));
        }
        return page;
    }
}
